﻿// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections.Generic;

namespace SnapObjects.Data.Odbc
{
    internal class OdbcAseFunctionParameterSchemaProvider : AseRoutineParameterSchemaProvider
    {
        public OdbcAseFunctionParameterSchemaProvider(DataContext dataContext) : base(dataContext)
        {
        }

        protected override ProcedureSchema CreateParameterSchema(
            string name,
            IReadOnlyList<AdoDbParameter> adoDbParameters,
            IReadOnlyList<DynamicModel> dbParameters)
        {
            var returnType = FunctionReturnType.Scalar;

            return new ProcedureSchema(name, adoDbParameters, returnType);
        }

        protected override string GetSchemaQuerySql(RoutineNameInfo nameInfo, ISqlGenerationHelper helper)
        {
            var sql = @"
SELECT obj.id as object_uniqueidentifier,
       col.name as parameter_name, 
       types.name as parameter_datatype, 
       case col.status2 when 1 then 'IN' else 'OUT' end as parameter_mode,
       col.prec as parameter_precision,
       col.scale as parameter_scale,
       null as parameter_defaultvalue
  FROM {0}sysobjects obj 
 INNER JOIN {0}sysusers u 
    ON obj.uid= u.uid 
  LEFT JOIN {0}syscolumns col 
    ON obj.id = col.id {1}
  LEFT JOIN {0}systypes types 
    ON col.usertype=types.usertype
 WHERE obj.type = 'SF' 
   AND obj.name = '{2}' {3}
 ORDER BY col.colid";

            var condition = String.Empty;

            if (!String.IsNullOrWhiteSpace(nameInfo.Schema))
            {
                var schema = helper.RemoveDelimitIdentifier(nameInfo.Schema);

                condition = $"AND u.name = '{schema}'";
            }

            var numCondition = String.Empty;

            if (nameInfo.Number > 0)
            {
                numCondition = $" AND col.number={nameInfo.Number}";
            }

            var name = helper.RemoveDelimitIdentifier(nameInfo.Name);

            var database = !String.IsNullOrWhiteSpace(nameInfo.Database) ? $"{nameInfo.Database}.." : String.Empty;

            return String.Format(sql, database, numCondition, name, condition);
        }
    }
}
